package com.coffee.framework.core.satoken;

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor;
import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.coffee.framework.common.util.StpAppUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * Sa Token 注册拦截器
 *
 * @author Kevin
 */
@Slf4j
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    private static final String APP_URL_PATTERN = "/front/**";

    private static final List<String> IGNORE_URL = Lists.newArrayList();

    static {
        IGNORE_URL.add("/");
        IGNORE_URL.add("/index");
        IGNORE_URL.add("/auth/system/login");
        IGNORE_URL.add("/auth/system/logout");
        IGNORE_URL.add("/auth/app/login");
        IGNORE_URL.add("/auth/app/logout");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器，自定义认证规则
        registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Methods", "*");
            res.setHeader("Access-Control-Max-Age", "3600");
            res.setHeader("Access-Control-Allow-Headers", "*");
            res.setHeader("Access-Control-Allow-Credentials", "true");
            SaRouter.match(SaHttpMethod.OPTIONS)
                    .free(r -> {
                    })
                    .back();
            if (SaRouter.isMatchCurrURI(APP_URL_PATTERN)) {
                SaRouter.match(APP_URL_PATTERN)
                        .notMatch(IGNORE_URL)
                        .check(() -> {
                            StpAppUtil.checkLogin();
                        });
            } else {
                SaRouter.match("/**")
                        .notMatch(IGNORE_URL)
                        .check(() -> {
                            StpUtil.checkLogin();
                        });
            }
        }));
        registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
    }

}
